import csv
import os
import re
import subprocess
import sys
from datetime import datetime
from pathlib import Path

import psutil
from airtest.core.android.adb import ADB
from airtest.core.api import connect_device, sleep, auto_setup, keyevent
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

from config import AutoDeliverConfig  # ← 新增配置模块


def resource_path(relative_path):
    """获取资源文件的路径，支持打包后执行的场景"""
    try:
        # PyInstaller 创建临时文件夹，并将路径储存在 _MEIPASS 中
        base_path = sys._MEIPASS
    except AttributeError:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

apk_path = resource_path("poco/drivers/android/lib/pocoservice-debug.apk")


# === 加载配置 ===
config = AutoDeliverConfig()

TASK_COUNT = config.get("task_count")
SALARY_FILTER = config.get("salary_filter")
JOB_KEYWORDS = config.get("job_keywords")
LOCATION_KEYWORDS = config.get("location_keywords")
CSV_ENABLE = config.get("csv_enable")
ADB_PATH = config.get("adb_path")
SCRCPY_PATH = Path(config.get("scrcpy_path"))

CSV_FILE = f"投递记录-{datetime.now().strftime('%Y-%m-%d')}.csv"


# === 工具函数 ===

def is_scrcpy_running() -> bool:
    return any(proc.info.get('name') == 'scrcpy.exe' for proc in psutil.process_iter(['name']))


def start_scrcpy():
    scrcpy_exe = SCRCPY_PATH / "scrcpy.exe"
    if not scrcpy_exe.exists():
        print(f"未找到 scrcpy.exe，跳过启动。路径：{scrcpy_exe}")
        return
    if not is_scrcpy_running():
        print("正在启动 scrcpy...")
        subprocess.Popen([str(scrcpy_exe)], creationflags=subprocess.CREATE_NO_WINDOW)
    else:
        print("scrcpy 已在运行")


def connect_android_device():
    ADB().adb_path = ADB_PATH
    return connect_device("Android://")


def is_range_within(range1: str, range2: str = SALARY_FILTER) -> bool:
    res1 = re.search(r'\d+-\d+', range1)
    if res1:
        range1 = res1.group(0)

    try:
        if "K" in range1.upper():
            min1, max1 = map(lambda x: int(x) * 1000, range1.upper().split('-'))
        else:
            min1, max1 = map(int, range1.split('-'))
        min2, max2 = map(int, range2.split('-'))
        return min1 >= min2 and max1 <= max2
    except Exception as e:
        print(f"薪资解析失败: {range1}, 错误: {e}")
        return False


def append_to_csv(file_path: str, data: list, header: list = None):
    file_exists = os.path.exists(file_path)
    try:
        with open(file_path, mode='a', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)
            if not file_exists and header:
                writer.writerow(header)
            writer.writerow(data)
    except Exception as e:
        print(f"写入 CSV 失败: {e}")


def swipe_left(poco):
    try:
        job = poco("com.hpbr.bosszhipin:id/tv_job_name", type="android.widget.TextView")
        job.swipe([-0.9, -0.1], duration=0.1)
    except Exception as e:
        print(f"滑动失败: {e}")


# === 核心逻辑 ===

def task_job(poco):
    try:
        job_name = poco("com.hpbr.bosszhipin:id/tv_job_name").get_text()
        salary = poco("com.hpbr.bosszhipin:id/tv_job_salary").get_text()
        location = poco("com.hpbr.bosszhipin:id/tv_required_location").get_text()
        boss = poco("com.hpbr.bosszhipin:id/tv_boss_name").get_text()
        btn_chat = poco("com.hpbr.bosszhipin:id/btn_chat")

        print(f"\n职位: {job_name} | 薪资: {salary} | 地点: {location} | Boss: {boss}")

        if CSV_ENABLE:
            append_to_csv(CSV_FILE, [job_name, salary, location, boss],
                          header=["职位", "薪资", "地点", "Boss"])

        if all([
            any(key in job_name for key in JOB_KEYWORDS),
            is_range_within(salary, SALARY_FILTER),
            any(key in location for key in LOCATION_KEYWORDS)
        ]):
            print("✔ 符合筛选，自动打招呼")
            btn_chat.click()
            sleep(0.5)
            keyevent("BACK")
            sleep(0.1)
        else:
            print("✘ 不符合筛选，跳过")
    except Exception as e:
        print(f"解析或操作失败: {e}")
    finally:
        swipe_left(poco)
        sleep(1)


# === 主流程 ===

def main():
    auto_setup(__file__)
    start_scrcpy()
    connect_android_device()
    poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)

    print(f"📢 共执行 {TASK_COUNT} 次自动投递任务...")
    for i in range(TASK_COUNT):
        print(f"\n=== 第 {i + 1} 次投递 ===")
        task_job(poco)


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        import traceback

        err_log = Path("error.log")
        err_log.write_text(traceback.format_exc(), encoding="utf-8")
        print("程序运行出错，详细信息写入 error.log")
        input("按回车键退出...")
